package route

import (
	"fmt"
	"github.com/antlabs/quickws"
	"net/http"
	"strings"
	"ubt-aio-service/app/utils"
)

type RouteHandler struct{}

type RouteItem struct {
	Method string
	Path   string
}

// ServeHTTP 重写ServeHTTP
func (h *RouteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 解决跨域
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token,token")
	w.Header().Add("Access-Control-Allow-Credentials", "true")
	w.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	w.Header().Set("content-type", "application/json;charset=UTF-8")
	switch r.URL.Path {
	case "/socket":
		execWs(w, r)
	default:
		// 获取路由列表
		routes := Routes()
		// 获取当前路由作为Key
		url := r.URL.String()
		urlArr := strings.Split(url, "?")
		url = url[:len(urlArr[0])]
		routerItem := RouteItem{Method: r.Method, Path: url}
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		// 查询路由是否存在
		if handler, ok := routes[routerItem]; ok {
			handler(r, w)
			return
		}
		w.WriteHeader(http.StatusNotFound)
	}
}

// execWs 调用服务
func execWs(w http.ResponseWriter, r *http.Request) {
	if c, err := quickws.Upgrade(w, r, quickws.WithServerIgnorePong(), quickws.WithServerCallback(&utils.WsHandler{})); err == nil {
		c.StartReadLoop()
	} else {
		fmt.Printf("Upgrade failed. The Reason is: %v\n", err.Error())
		return
	}
}
